package net.zoneland.zrdp.common.utils.file;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import net.zoneland.zrdp.common.utils.spring.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.zoneland.zrdp.common.config.ZonevueConfig;
import net.zoneland.zrdp.common.constant.Constants;

/**
 * 图片处理工具类
 *
 * @author zonevue
 */
public class ImageUtils
{
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class);
    private ImageUtils() {
        throw new IllegalStateException("Utility class");
    }
    public static byte[] getImage(String imagePath)
    {
        final InputStream is = getFile(imagePath);
        try {
            return IOUtils.toByteArray(is);
        } catch (final Exception e) {
            LOGGER.error("图片加载异常 {}", imagePath, e);
            return new byte[0];
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    public static InputStream getFile(final String imagePath) {
            final byte[] result = readFile(imagePath);
            return new ByteArrayInputStream(result);
    }

    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(final String url) {
        if (url.startsWith("http")) {
            return readFromNetwork(url);
        } else {
            return readFromLocal(url);
        }
    }

    private static byte[] readFromNetwork(final String url) {
        try {
            final URL urlObj = new URL(url);
            final URLConnection urlConnection = urlObj.openConnection();
            urlConnection.setConnectTimeout(30 * 1000);
            urlConnection.setReadTimeout(60 * 1000);
            urlConnection.setDoInput(true);
            try (final InputStream in = urlConnection.getInputStream()) {
                return IOUtils.toByteArray(in);
            }
        } catch (final MalformedURLException e) {
            LOGGER.error("Invalid URL {}", url, e);
        } catch (final IOException e) {
            LOGGER.error("Error reading from URL {}", url, e);
        }
        return new byte[0];
    }

    private static byte[] readFromLocal(final String url) {
        final Path basePath = Paths.get(SpringUtils.getBean(ZonevueConfig.class).getProfile());
        final String downloadPath = StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
        final Path normalizedPath = basePath.resolve(downloadPath).normalize();
        // 检查规范化后的路径是否以安全的基础路径开头
        if (!normalizedPath.startsWith(basePath)) {
            try (final InputStream in = Files.newInputStream(Paths.get(downloadPath))) {
                return IOUtils.toByteArray(in);
            } catch (final IOException e) {
                LOGGER.error("Error reading from local file {}", downloadPath, e);
            }
        }
        return new byte[0];
    }

}
